package okhttp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpTest {
	private static String url = "https://www.baidu.com";
	private static OkHttpClient client = new OkHttpClient();
	
	private static void testGet() {
		Request request = new Request.Builder().get().url(url).build();
		client.newCall(request).enqueue(new Callback() {

			public void onFailure(Call call, IOException e) {
				System.out.println("call fail");
			}

			public void onResponse(Call call, Response response) throws IOException {
				if(response.isSuccessful()) { // 成功
					String res = response.body().string();
					System.out.println(res);
				}
			}
			
		});
	}
	
	public static void testPost() {
		// form表单形式
//		RequestBody body = new FormBody.Builder()
//				.add("username", "guweiqiang")
//				.add("password", "password")
//				.build();

		// JSON参数形式
		String json = "";
		RequestBody body = RequestBody.create(MediaType.parse("applicatio/json; charset=utf-8"), json);
		
		Request request = new Request.Builder().post(body).url(url).build();
		client.newCall(request).enqueue(new Callback() {

			public void onFailure(Call call, IOException e) {
				System.out.println("call fail");
			}

			public void onResponse(Call call, Response response) throws IOException {
				if(response.isSuccessful()) { // 成功
					String res = response.body().string();
					System.out.println(res);
				}
			}
			
		});
	}
	
	public static void testFileUpload() {
		File file = new File("c:/111.pdf");
		String originalName = file.getName();
		RequestBody fileBody = RequestBody.create(MediaType.parse("image/png"), file);
		RequestBody requestBody = new MultipartBody.Builder()
				.setType(MultipartBody.FORM)
				.addFormDataPart("file", originalName, fileBody)
				.build();
		String url = "http://localhost:8050/upload";
		Request request = new Request.Builder().url(url).post(requestBody).build();
		client.newCall(request).enqueue(new Callback() {

			public void onFailure(Call call, IOException e) {
				System.out.println("call fail");
			}

			public void onResponse(Call call, Response response) throws IOException {
				if(response.isSuccessful()) { // 成功
					String res = response.body().string();
					System.out.println(res);
				}
			}
			
		});
	}
	
	public static void testDownload() {
		String url = "http://c.hiphotos.baidu.com/image/h%3D300/sign=a04ba5c277f40ad10ae4c1e3672d1151/d439b6003af33a87436092e0ca5c10385343b53f.jpg";
		Request request = new Request.Builder().url(url).build();
		client.newCall(request).enqueue(new Callback() {

			public void onFailure(Call call, IOException e) {
				System.out.println("call fail");
			}

			public void onResponse(Call call, Response response) throws IOException {
				if(response.isSuccessful()) { // 成功
					downlodefile(response, "http://c.hiphotos.baidu.com/image/h%3D300/sign=a04ba5c277f40ad10ae4c1e3672d1151/d439b6003af33a87436092e0ca5c10385343b53f.jpg", "d439b6003af33a87436092e0ca5c10385343b53f.jpg");
				}
			}
			
		});
	}


	protected static void downlodefile(Response response, String url, String fileName) {
		InputStream is = null;
		byte[] buf = new byte[2048];
		int len = 0;
		FileOutputStream fos = null;
		
		try {
			is = response.body().byteStream();
			long total = response.body().contentLength();
			File file = new File(url, fileName);
			long sum = 0;
			int progress = 0; // 进度条
			while((len=is.read(buf)) != -1) {
				fos.write(buf, 0, len);
				sum += len;
				progress = (int)(sum * 1.0f / total * 100);
				System.out.println(progress);
			}
			fos.flush();
			System.out.println("download success.");
		} catch (Exception e) {
			
		} finally {
			try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }

		}
		
	}

	public static void main(String[] args) {
//		testGet();
//		testPost();
//		testFileUpload();
		testDownload();
	}

}
